import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  StatusBar,
  ActivityIndicator,
  FlatList,
  TouchableWithoutFeedback,
  Image,
  StyleSheet
} from 'react-native';
import { MineScreenProps } from '../../types/NavigationTypes';

type VideoData = {
  type: string;
  data: {
    title: string;
    cover: { feed: string };
    author: { icon: string; name: string };
    category: string;
  };
};

const MineScreen: React.FC<MineScreenProps> = ({ navigation }) => {
  const [ready, setReady] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [videos, setVideos] = useState<{ key: number; value: VideoData }[]>([]);

  useEffect(() => {
    _fetchData();
  }, []);

  const _fetchData = async () => {
    try {
      let response = await fetch('http://baobab.kaiyanapp.com/api/v4/tabs/selected');
      let responseText = await response.json();
      let arrData = responseText.itemList.filter((item: VideoData) => item.type === 'video');

      let i = 0;
      let arrList = arrData.map((item: VideoData) => ({ key: i++, value: item }));
      setVideos(arrList);
      setReady(false);
      setRefreshing(false);
    } catch (e) {
      console.error(e);
      setVideos([]);
      setReady(false);
      setRefreshing(false);
    }
  };

  const _refreshData = () => {
    setRefreshing(true);
    _fetchData();
  };

  const _renderItem = ({ item }: { item: { key: number; value: VideoData } }) => {
    const data = item.value.data;
    return (
      <TouchableWithoutFeedback onPress={() => _onVideoItemClick(item.value)}>
        <View style={styles.contentView}>
          <Image style={styles.cover} source={{ uri: data.cover.feed }} />
          <View style={styles.bottomView}>
            <Image style={styles.avatar} source={{ uri: data.author.icon }} />
            <View style={styles.titleView}>
              <Text numberOfLines={1} style={styles.title}>{data.title}</Text>
              <Text numberOfLines={1} style={styles.category}>{`${data.author.name} / #${data.category}`}</Text>
            </View>
            <Image style={styles.share} source={require('../../../assets/images/icon_action_share_grey.png')} />
          </View>
        </View>
      </TouchableWithoutFeedback>
    );
  };

  const _onVideoItemClick = (item: VideoData) => {
    navigation.navigate('Video', { data: item });
  };

  return (
    <>
      <StatusBar barStyle="dark-content" backgroundColor={'#ffffff'}/>
      <View style={styles.container}>
        {ready ? (
          <ActivityIndicator size="large" style={{ marginTop: 100 }} />
        ) : (
          <FlatList
            data={videos}
            onRefresh={_refreshData}
            refreshing={refreshing}
            keyExtractor={(item) => item.key.toString()}
            renderItem={_renderItem}
          />
        )}
      </View>
    </>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  contentView: {
    backgroundColor: '#fff',
    flex: 1,
    paddingLeft: 12,
    paddingRight: 12,
    paddingTop: 6,
    paddingBottom: 6,
  },
  cover: {
    flex: 1,
    height: 260,
    resizeMode: 'cover',
    borderRadius: 6,
  },
  bottomView: {
    flexDirection: 'row',
    marginTop: 10,
    height: 40,
  },
  avatar: {
    width: 42,
    height: 42,
    resizeMode: 'cover',
    borderRadius: 21,
  },
  titleView: {
    marginLeft: 8,
    flex: 1,
  },
  title: {
    fontSize: 13,
    color: '#333',
    fontWeight: 'bold',
    marginTop: 6,
  },
  category: {
    fontSize: 12,
    color: '#999',
  },
  share: {
    width: 30,
    height: 30,
    alignSelf: 'flex-end',
  },
});

export default MineScreen;